package model

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/jinzhu/gorm"
	"time"
	"xinyu/MyLog"
	"xinyu/setting"

	// MySQL driver.
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type DataBase struct {
	MyDB *gorm.DB
}

var DB *DataBase
var RedisTemplate *redis.Client

func InitRedis(redisSetting *setting.RedisSettingS) {
	RedisTemplate = redis.NewClient(&redis.Options{
		Addr:     redisSetting.Addr,
		Password: redisSetting.Password, // no password set
		DB:       redisSetting.Num,      // use default DB
	})
}

func (db *DataBase) Init(databaseSetting *setting.DatabaseSettingS) {
	DB = &DataBase{
		MyDB: getMySqlDB(databaseSetting),
	}
}

func (db *DataBase) Close() {
	DB.MyDB.Close()
}

func initSelfDB(databaseSetting *setting.DatabaseSettingS) *gorm.DB {
	db := openDB(
		databaseSetting.DBType,
		databaseSetting.Username,
		databaseSetting.Password,
		databaseSetting.Host,
		databaseSetting.DBName,
		databaseSetting.ParseTime,
		databaseSetting.MaxIdleConns,
		databaseSetting.MaxOpenConns,
	)
	return db
}

func getMySqlDB(databaseSetting *setting.DatabaseSettingS) *gorm.DB {
	return initSelfDB(databaseSetting)
}

func openDB(dbType, username, password, addr, name string, parseTime bool, maxIdleConn, maxOpenConn int) *gorm.DB {
	config := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true&charset=utf8&parseTime=%t&loc=%s",
		username,
		password,
		addr,
		name,
		parseTime,
		"Local")
	db, err := gorm.Open(dbType, config)
	if err != nil {
		MyLog.Log.Errorf("Database connection failed. Database name: %s,Eroor:%s", name, err.Error())
	}

	setupDB(db, maxIdleConn, maxOpenConn)
	return db
}

func setupDB(db *gorm.DB, maxIdleConn, maxOpenConn int) {
	// 用于设置闲置的连接数.
	db.DB().SetMaxIdleConns(maxIdleConn)

	// 用户设置最大连接数
	db.DB().SetMaxOpenConns(maxOpenConn)

	// 用户设置连接可复用最大时间
	db.DB().SetConnMaxLifetime(time.Hour)
}
